package one.chapter_1.stack.test;

import one.chapter_1.stack.LinkedStack;
import one.chapter_1.stack.ResizingArrayStack;
import one.chapter_1.stack.Stack;

public class Evaluate {


    public static void main(String [] args){

        String expression="(1+((3-2)*(4*5)))";
        Evaluate evaluate=new Evaluate();
        System.out.println(evaluate.evaluate(expression));

    }


    public double evaluate(String expression){
        Stack<Double> vals=new LinkedStack<Double>();
        Stack<Character> operators=new LinkedStack<Character>();

        for (int i=0;i<expression.length();i++){
            char ch=expression.charAt(i);
            if (ch=='('){
                //忽略
            }else if (ch==')'){
                //需要操作
                double v1=vals.pop();
                double v2=vals.pop();
                char op=operators.pop();
                switch (op){
                    case '+':
                        vals.push(v2+v1);
                        break;
                    case '-':
                        vals.push(v2-v1);
                        break;
                    case '*':
                        vals.push(v2*v1);
                        break;
                    case '/':
                        vals.push(v2/v1);
                        break;
                }

            }else if (ch=='+'){
                operators.push(ch);
            }else if (ch=='-'){
                operators.push(ch);
            }else if (ch=='*'){
                operators.push(ch);
            }else if (ch=='/'){
                operators.push(ch);
            }else if (Character.isDigit(ch)){
                String digit=String.valueOf(ch);
                vals.push(Double.parseDouble(digit));
            }
        }



        return vals.pop();

    }
}
